﻿using System;
using System.Configuration;

using System.Text;
using Portal.Environment;
using System.Data;

namespace LinqChat
{
    public partial class Chatroom : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
    {
        private string _callBackStatus;
        string ChatWithLoginName
        {
            get
            {
                return lblChatWithAccount.Text;
            }
        }
        string ChatWithSex
        {
            get
            {
                return lblChatWithSex.Text;
            }
        }

        string ChatWithUserId
        {
            get
            {
                return (string)Request["ChatWithUserId"];
            }
        }
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //e.Authenticated = true;
                if (Environments.CurrentLoginUser == null)
                {
                    Response.Redirect("~/Login.aspx");
                    return;
                }
                Session["ChatUserID"] = Environments.CurrentLoginUser.UserId;
                Session["ChatLoginName"] = Environments.CurrentLoginUser.LoginName;

                // for simplity's sake we're going to assume that a
                // roomId was passed in the query string and that
                // it is an integer
                // note: in reality you would check if the roomId is empty
                // and is an integer
                Portal.SystemWebParts.User.UserCls ChatWithUserCls = new Portal.SystemWebParts.User.UserBLL().CreateModel(ChatWithUserId);
                if (ChatWithUserCls == null)
                {
                    return;
                }

                string r = (string)Request["r"];
                if (r == null) r = "0";
                if (r.Equals("1"))
                {
                    ChatServiceBll.FinishRequestChat(ChatWithUserCls.UserId);
                }
                lblChatWithSex.Text = ChatWithUserCls.Sex;
                lblChatWithAccount.Text = ChatWithUserCls.LoginName;// +" / " + ChatWithUserCls.FullName;
                lblChatWithAccountFullName.Text = ChatWithUserCls.FullName;
                this.GetLoggedInUsers();
                this.InsertMessage(ChatWithUserCls.LoginName+" bắt đầu chat lúc " + DateTime.Now.ToString(),1);
                this.GetMessages();

                // create a call back reference so we can log-out user when user closes the browser
                string callBackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "LogOutUser", "");
                string logOutUserCallBackScript = "function LogOutUserCallBack(arg, context) { " + callBackReference + "; }";
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "LogOutUserCallBack", logOutUserCallBackScript, true);
            }
        }

        
        protected void BtnSend_Click(object sender, EventArgs e)
        {
            if (txtMessage.Text.Length > 0)
            {
                this.InsertMessage(null,0);
                this.GetMessages();
                txtMessage.Text = String.Empty;
                //ScriptManager1.SetFocus(txtMessage.ClientID);
            }
        }

        protected void Timer1_OnTick(object sender, EventArgs e)
        {
            this.GetLoggedInUsers();
            this.GetMessages();

            if ((string)Session["IsChatroomInFocus"] == null)
                txtMessage.Text = String.Empty;
               // ScriptManager1.SetFocus(txtMessage);
        }

        /// <summary>
        /// This will insert the passed text to the message table in the database
        /// </summary>
        private void InsertMessage(string text,int Auto)
        {
            string MsgText="";
            string ColorText="black";
            if (String.IsNullOrEmpty(text))
            {
                MsgText = txtMessage.Text.Replace("<", "");
                ColorText= ddlColor.SelectedValue;
            }
            else
            {
                MsgText = text;
                ColorText = "gray";
            }

            Portal.Environment.ChatServiceBll.AddMessage(
                1,
                (string)Session["ChatUserID"],
                Portal.Environment.Environments.CurrentLoginUser.LoginName,
                ChatWithUserId,
                ChatWithLoginName,
                MsgText,
                ColorText,
                ChatWithSex,
                Auto);
        }


       
        private void GetLoggedInUsers()
        {
            // holds the names of the users shown in the chatroom
            litUsers.Text = new ChatServices().GetLoggedInUsers() ;// sb.ToString();
        }

        /// <summary>
        /// Get the last 20 messages for this room
        /// </summary>
        private void GetMessages()
        {
            try
            {
                DataTable dtMessage = ChatServiceBll.ReadingMessage(Environments.CurrentLoginUser.UserId, ChatWithUserId);
                if (dtMessage.Rows.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    int ctr = 0;    // toggle counter for alternating color

                    for (int iIndex = 0; iIndex < dtMessage.Rows.Count; iIndex++)
                    {
                        // alternate background color on messages
                        string MsgText = (string)dtMessage.Rows[iIndex]["Text"];
                        string ColorText = (string)dtMessage.Rows[iIndex]["Color"];
                        string FromLoginName = (string)dtMessage.Rows[iIndex]["FromLoginName"];
                        string Sex = (string)dtMessage.Rows[iIndex]["Sex"];
                        if (ctr == 0)
                        {
                            sb.Append("<div style='padding: 10px;'>");
                            ctr = 1;
                        }
                        else
                        {
                            sb.Append("<div style='background-color: #EFEFEF; padding: 10px;'>");
                            ctr = 0;
                        }

                        if (Sex.ToLower() == "m")
                            sb.Append("<img src='Images/manIcon.gif' style='vertical-align:middle' alt=''>  " + FromLoginName + ": <span style=\"color:" + ColorText + "\">" + MsgText + "</span></div>");
                        else
                            sb.Append("<img src='Images/manIcon.gif' style='vertical-align:middle' alt=''>  " + FromLoginName + ": <span style=\"color:" + ColorText + "\">" + MsgText + "</span></div>");
                    }

                    litMessages.Text = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                ex.Source = "";
            }
        }

        #region ICallbackEventHandler Members

        string  System.Web.UI.ICallbackEventHandler.GetCallbackResult()
        {
            return _callBackStatus;
        }

        void  System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
        {
            _callBackStatus = "failed";
             ChatServiceBll.LogOffUser(Environments.CurrentLoginUser.UserId);
            // insert a message that this user has logged out
            this.InsertMessage(Environments.CurrentLoginUser.LoginName+" vừa thoát khỏi hệ thống chat lúc " + DateTime.Now.ToString(),1);

            _callBackStatus = "success";
        }

        #endregion
        protected void cmdClearChat_Click(object sender, EventArgs e)
        {
            try
            {
                ChatServiceBll.ClearChat(Environments.CurrentLoginUser.UserId);
            }
            catch (Exception ex)
            {
                ex.Source = "";
            }
        }
}
}
